package cn.mesmile.shiro.module.common.controller;

import cn.mesmile.shiro.module.user.dto.UserQueryDTO;
import cn.mesmile.shiro.utils.JwtUtil;
import com.baomidou.mybatisplus.extension.api.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.*;

import static com.baomidou.mybatisplus.core.toolkit.IdWorker.getId;

/**
 * @author zb
 * @date 2021/2/7 22:51
 * @Description:
 */
@Slf4j
@RestController
public class CommonController {


    @GetMapping("/pub/need_login")
    public Map<String,Object> needLogin(){
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("message",">>>>>>>>>>> 请登录后访问。");
        return map;
    }

    @GetMapping("/user/get")
    public Map<String,Object> user(){
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("message",">>>>>>>>>>> 登录成功后才可以访问的数据");
        return map;
    }

    /**
     * 这里使用配置文件里面的 退出登录功能
     * @return
     */
//    @GetMapping("/logout")
//    public Map<String,Object> logout(HttpServletRequest request){
//
//        Subject subject = SecurityUtils.getSubject();
//        subject.logout();
//        Map<String, Object> map = new HashMap<>();
//        map.put("code",200);
//        map.put("message","退出登录。");
//        return map;
//
//    }

    @GetMapping("/pub/not_permit")
    public Map<String,Object> notPermit(){
        Map<String, Object> map = new HashMap<>();
        map.put("code",401);
        map.put("message","当前用户没有权限");
        return map;
    }

    @GetMapping("/authc/get")
    public Map<String,Object> authc(){
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("message",">>>>> 这是登录成功的用户访问的页面");
        return map;
    }

    @GetMapping("/pub/index")
    public Map<String,Object> index(){
        List<String> strings = new ArrayList<>(Arrays.asList("1", "2", "3"));
        Map<String, Object> map = new HashMap<>();
        map.put("code",200);
        map.put("message","访问首页成功");
        map.put("data",strings);
        return map;
    }

    @PostMapping("/pub/login")
    public Map<String,Object> login(@RequestBody UserQueryDTO userQueryDTO, HttpServletRequest request, HttpServletResponse response){

        boolean loginSuccess = false;
        // 获取当前主体
        Subject subject = SecurityUtils.getSubject();
        // 输入账号和密码
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userQueryDTO.getUsername(),  userQueryDTO.getPassword());

        // 设置 rememberMe
//        usernamePasswordToken.setRememberMe(true);

        Map<String, Object> map = new HashMap<>();

        try {
            // 登录认证
            subject.login(usernamePasswordToken);
            loginSuccess = true;
            boolean authenticated = subject.isAuthenticated();
            System.out.println("authenticated = " + authenticated);
        } catch  ( UnknownAccountException uae ) {
            log.error(">>>>>>>>>>>>> 账号名错误： {}", userQueryDTO.getUsername());
        } catch  ( IncorrectCredentialsException ice ) {
            log.error(">>>>>>>>>>>>> 密码错误： {}", userQueryDTO.getPassword());
//            throw new RuntimeException(">>>>>>>>>>>>> 密码错误");
        } catch  ( LockedAccountException lae ) {
            log.error(">>>>>>>>>>>>> 账号被锁定： {}", userQueryDTO.getUsername());
            throw new RuntimeException(">>>>>>>>>>>>> 账号被锁定");
        } catch  ( ExcessiveAttemptsException eae ) {
            log.error(">>>>>>>>>>>>> 尝试次数过多异常： {},  {}", userQueryDTO.getUsername(),eae.getMessage());
//            throw new RuntimeException(">>>>>>>>>>>>> 尝试次数过多异常");
        } catch ( AuthenticationException ae ) {
            log.error(">>>>>>>>>>>>> 身份认证异常： {}", userQueryDTO.getUsername());
            throw new RuntimeException(">>>>>>>>>>>>> 身份认证异常");
        }
        String token = null;
        if(loginSuccess){
            // 生产token
            token = JwtUtil.sign(userQueryDTO.getUsername(), System.currentTimeMillis());
        }

//        Session session = subject.getSession();
//        Serializable sessionId = session.getId();
//
//        session.setAttribute("username",userQueryDTO.getUsername());
//        System.out.println("session.getHost() = " + session.getHost());

        List<String> strings = new ArrayList<>(Arrays.asList("1", "2", "3"));

        map.put("code",200);
        map.put("message","访问首页成功");
        map.put("data",strings);
        map.put("token",token);
        return map;
    }



}
